package com.demo.context;

import com.alibaba.fastjson.JSON;
import com.demo.model.UserContext;
import com.demo.model.UserDto;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * TransmitUserInfoFeighClientIntercepter
 *
 * @author liujin
 * @date 2020/12/9 21:52
 */
@Slf4j
public class TransmitUserInfoFeighClientIntercepter implements RequestInterceptor {


    public TransmitUserInfoFeighClientIntercepter() {
    }

    @Override
    public void apply(RequestTemplate requestTemplate) {
        //从应用上下文中取出user信息，放入Feign的请求头中
        UserDto user = UserContext.getUser();
        if (user != null) {
            String encodeToString = Base64.getEncoder().encodeToString(JSON.toJSONString(user).getBytes(StandardCharsets.UTF_8));
            requestTemplate.header(UserContext.KEY_USERINFO_IN_HTTP_HEADER, encodeToString);
        }
    }
}
